//
//  HHMonthPickerView.m
//  Pod
//
//  Created by Basic on 2018/12/27.
//

#import "HHMonthPickerView.h"
#import <BCFoundation/BCFoundationUtils.h>
#import <BCFoundation/NSDate+BCHelper.h>
#import <BCFoundation/NSArray+BCHelper.h>
#import <BCUIKit/UIView+BCHelper.h>
#import <BCComConfigKit/BCComConfigKit.h>

#define kHHMonthPickerView_PickH     200
#define kHHMonthPickerView_ToolBarH  44

@interface HHMonthPickerView()<UIPickerViewDelegate, UIPickerViewDataSource>
@property (nonatomic, strong) NSMutableArray<NSNumber *> *years;
@property (nonatomic, strong) NSMutableArray<NSNumber *> *months;
/** 最大年份，默认0，不限制 */
@property (nonatomic, assign) NSInteger maxYear;
/** 最小年份，默认0，不限制 */
@property (nonatomic, assign) NSInteger minYear;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) UILabel *splitLb;
@end


@implementation HHMonthPickerView
//MARK: - system
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubViews];
    }
    return self;
}
-(void)awakeFromNib {
    [super awakeFromNib];
    [self setupSubViews];
}
- (void)dealloc
{
    BCLogDealloc();
}

//MARK: - 初始化
- (void)setupSubViews {
    if (_containerView) {
        return;
    }
    _dateMode = HHMonthPickerMode_YearMonth;
    _showAllMonth = YES;
    self.clipsToBounds = YES;
    self.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.4f];
    @BCWeakify(self);
    [self bc_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        @BCStrongify(self);
        CGPoint touchPoint = [gestureRecoginzer locationInView:self];
        if (CGRectContainsPoint(self.containerView.frame, touchPoint)) {
            return ;
        }
        [self hideAnimate:YES];
    }];
    //容器view
    [self addSubview:self.containerView];
    //add tool bar
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, kBCSCREEN_WIDTH, kHHMonthPickerView_ToolBarH)];
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelBarItemAction:)];
    cancelItem.tintColor = BCComConfig.config.lightBlackColor;
    
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:BCLOC(@"确认") style:UIBarButtonItemStyleDone target:self action:@selector(doneBarItemAction:)];
    doneItem.tintColor = BCComConfig.config.defaultColor;
    [toolBar setItems:@[cancelItem,flexibleSpace,doneItem]];
    [self.containerView addSubview:toolBar];
    //add split line
    [self.containerView addSubview:self.splitLb];
    //add pickerView
    [self.containerView addSubview:self.pickerView];
}

//MARK: - public
static HHMonthPickerView *kHHMonthPickerViewInstance = nil;
+(instancetype)zh_pickView:(UIView *)superView {
    if (!superView) {
        return nil;
    }
    if (kHHMonthPickerViewInstance) {
        [kHHMonthPickerViewInstance hideAnimate:NO];
    }
    HHMonthPickerView *pickerView = [[HHMonthPickerView alloc] initWithFrame:CGRectMake(0, 0, superView.bc_width, superView.bc_height)];
    pickerView.alpha = 0;
    [superView addSubview:pickerView];
    return pickerView;
}

- (void)reloadData {
    //默认选择当前年份
    if (self.dateMode == HHMonthPickerMode_YearMonth || self.dateMode == HHMonthPickerMode_Year) {
        if (self.selectedYear<=0) {
            NSDate *selectedDate = self.selectedDate?:[NSDate date];
            NSString *currentYearStr = [selectedDate bc_formatDateWithFormat:@"yyyy"];
            if ([currentYearStr respondsToSelector:@selector(integerValue)]) {
                self.selectedYear = [currentYearStr integerValue];
            }
        }
    }
    //默认选择当前月份
    if (self.dateMode == HHMonthPickerMode_YearMonth || self.dateMode == HHMonthPickerMode_Month) {
        if (self.selectedMonth<=0) {
            NSDate *selectedDate = self.selectedDate?:[NSDate date];
            NSString *currentMonthStr = [selectedDate bc_formatDateWithFormat:@"MM"];
            if ([currentMonthStr respondsToSelector:@selector(integerValue)]) {
                self.selectedMonth = [currentMonthStr integerValue];
            }
        }
    }
    //最大年份
    if (self.maxDate) {
        NSString *yearStr = [self.maxDate bc_formatDateWithFormat:@"yyyy"];
        if ([yearStr respondsToSelector:@selector(integerValue)]) {
            self.maxYear = [yearStr integerValue];
        }
    } else {
        //默认当前年份 + 30
        NSString *yearStr = [[NSDate date] bc_formatDateWithFormat:@"yyyy"];
        if ([yearStr respondsToSelector:@selector(integerValue)]) {
            self.maxYear = [yearStr integerValue] + 30;
        }
    }
    
    //最小年份
    if (self.minDate) {
        NSString *yearStr = [self.minDate bc_formatDateWithFormat:@"yyyy"];
        if ([yearStr respondsToSelector:@selector(integerValue)]) {
            self.minYear = [yearStr integerValue];
        }
    } else {
        //默认当前年份 - 30
        NSString *yearStr = [[NSDate date] bc_formatDateWithFormat:@"yyyy"];
        if ([yearStr respondsToSelector:@selector(integerValue)]) {
            self.minYear = [yearStr integerValue] - 30;
        }
    }
    //构造年份数据和月份数据
    NSInteger selectYearIndex = -1;//选择的年 索引
    if (self.dateMode == HHMonthPickerMode_YearMonth || self.dateMode == HHMonthPickerMode_Year) {
        self.years = [[NSMutableArray alloc] init];
        for (NSInteger i=0; i<=self.maxYear-self.minYear; i++) {
            if (self.selectedYear>0 && self.minYear+i == self.selectedYear) {
                selectYearIndex = i;
            }
            [self.years addObject:@(self.minYear+i)];
        }
    }
    NSInteger selectMonthIndex = -1;//选择的月 索引
    if (self.dateMode == HHMonthPickerMode_YearMonth || self.dateMode == HHMonthPickerMode_Month) {
        self.months = [[NSMutableArray alloc] init];
        if (self.showAllMonth) {
            //显示全部月份
            for (int i=0; i<13; i++) {
                if (i == self.selectedMonth) {
                    selectMonthIndex = i;
                }
                [self.months addObject:@(i)];
            }
        } else {
            //不显示全部月份
            for (int i=0; i<12; i++) {
                if ((i+1) == self.selectedMonth) {
                    selectMonthIndex = i;
                }
                [self.months addObject:@(i+1)];
            }
        }
    }
    //重新加载 pickerCiew
    [self.pickerView reloadAllComponents];
    if (selectYearIndex>=0) {
        [self.pickerView selectRow:selectYearIndex inComponent:0 animated:NO];
    }
    if (selectMonthIndex>=0) {
        if (self.dateMode == HHMonthPickerMode_YearMonth) {
            [self.pickerView selectRow:selectMonthIndex inComponent:1 animated:NO];
        } else if (self.dateMode == HHMonthPickerMode_Month) {
            [self.pickerView selectRow:selectMonthIndex inComponent:0 animated:NO];
        }
    }
}
- (void)showAnimate:(BOOL )animate {
    if (self.alpha !=0) {
        return;
    }
    self.hidden = NO;
    [UIView animateWithDuration:0.25f animations:^{
        [self.containerView setBc_y:self.bc_height-self.containerView.bc_height];
        self.alpha = 1;
    }];
}

- (void)hideAnimate:(BOOL )animate {
    if (self.alpha !=1) {
        return;
    }
    if (animate) {
        self.hidden = NO;
        [UIView animateWithDuration:0.25f animations:^{
            [self.containerView setBc_y:self.bc_height];
            self.alpha = 0;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
            self.hidden = YES;
            kHHMonthPickerViewInstance = nil;
        }];
    } else {
        self.alpha = 0;
        self.hidden = YES;
        [self removeFromSuperview];
        kHHMonthPickerViewInstance = nil;
    }
}

//MARK: - Event Response
- (void)cancelBarItemAction:(id)sender {
    [self hideAnimate:YES];
}
- (void)doneBarItemAction:(id)sender {
    if (self.dateMode == HHMonthPickerMode_YearMonth ) {
        //年 & 月
        self.selectedYear = [[self.years bc_safeObjectAtIndex:[self.pickerView selectedRowInComponent:0]] integerValue];
        self.selectedMonth = [[self.months bc_safeObjectAtIndex:[self.pickerView selectedRowInComponent:1]] integerValue];
        if (self.selectedYear<=0 || self.selectedMonth<=0) {
            _selectedDate = nil;
        } else {
            NSString *selectedDateStr = [NSString stringWithFormat:@"%d年%d月", (int)self.selectedYear, (int)self.selectedMonth];
            _selectedDate = [NSDate bc_formatDate:selectedDateStr withStyle:@"yyyy年MM月"];
        }
    } else if (self.dateMode == HHMonthPickerMode_Year) {
        //年
        self.selectedYear = [[self.years bc_safeObjectAtIndex:[self.pickerView selectedRowInComponent:0]] integerValue];
    } else if (self.dateMode == HHMonthPickerMode_Month) {
        //月
        self.selectedMonth = [[self.months bc_safeObjectAtIndex:[self.pickerView selectedRowInComponent:0]] integerValue];
    } else {
        //其他
    }
    [self hideAnimate:YES];
    if (self.confirmBlock) {
        self.confirmBlock(self, self.selectedYear, self.selectedMonth);
    }
}

//MARK: - UIPickerViewDataSource
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    if (self.dateMode == HHMonthPickerMode_YearMonth ) {
        //年 & 月
        return 2;
    } else if (self.dateMode == HHMonthPickerMode_Year || self.dateMode == HHMonthPickerMode_Month) {
        //年 || 月
        return 1;
    } else {
        return 0;
    }
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (self.dateMode == HHMonthPickerMode_YearMonth ) {
        //年 & 月
        if (component == 0) {
            return self.years.count;
        } else if (component == 1) {
            return self.months.count;
        } else {
            return 0;
        }
    } else if (self.dateMode == HHMonthPickerMode_Year) {
        //年
        return self.years.count;
    } else if (self.dateMode == HHMonthPickerMode_Month) {
        //月
        return self.months.count;
    } else {
        return 0;
    }
}
//显示的标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (self.dateMode == HHMonthPickerMode_YearMonth ) {
        //年 & 月
        if (component == 0) {
            NSNumber *yearNum = self.years[row];
            return [NSString stringWithFormat:@"%@年", yearNum];
        } else if (component == 1) {
            NSNumber *monthNum = self.months[row];
            if ([monthNum integerValue] == 0) {
                //全部
                return BCLOC(@"全部");
            } else {
                return [NSString stringWithFormat:@"%@月", monthNum];
            }
        } else {
            return @"";
        }
    } else if (self.dateMode == HHMonthPickerMode_Year) {
        //年
        NSNumber *yearNum = self.years[row];
        return [NSString stringWithFormat:@"%@年", yearNum];
    } else if (self.dateMode == HHMonthPickerMode_Month) {
        //月
        NSNumber *monthNum = self.months[row];
        if ([monthNum integerValue] == 0) {
            //全部
            return BCLOC(@"全部");
        } else {
            return [NSString stringWithFormat:@"%@月", monthNum];
        }
    } else {
        return @"";
    }
}

//MARK: - getter
-(UILabel *)splitLb {
    if (!_splitLb) {
        _splitLb = [[UILabel alloc] initWithFrame:CGRectMake(0, kHHMonthPickerView_ToolBarH-0.5, self.bc_width, 0.5)];
        _splitLb.backgroundColor = BCComConfig.config.splitColor;
    }
    return _splitLb;
}
-(UIView *)containerView {
    if (!_containerView) {
        _containerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.bc_height, kBCSCREEN_WIDTH, kHHMonthPickerView_ToolBarH + kHHMonthPickerView_PickH + kBCScreenSafeAreaBottom)];
        _containerView.backgroundColor = UIColor.whiteColor;
        _containerView.clipsToBounds = YES;
    }
    return _containerView;
}
-(UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, kHHMonthPickerView_ToolBarH, kBCSCREEN_WIDTH, kHHMonthPickerView_PickH)];
        _pickerView.backgroundColor = [UIColor whiteColor];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
    }
    return _pickerView;
}
@end
